﻿using System;
using System.Collections.Generic;

namespace PricePortalLib
{
    //Classinvariant: After initialization cache is never null; 
    public class IFindItemImpl : IFindItem
    {
        private IItemCache cache;
        private ISearchSubSupplier searchSubSupplier;
        private uint cacheExpireTime;

        public IFindItemImpl(IItemCache cache, ISearchSubSupplier searchSubSupplier, uint cacheExpireTime)
        {
            this.cache = cache;
            this.searchSubSupplier = searchSubSupplier;
            this.cacheExpireTime = cacheExpireTime;
        }

        public IFindItemImpl(IItemCache cache, ISearchSubSupplier searchSubSupplier) : this(cache, searchSubSupplier, 0)
        {}

        //Precondition: IItemCache.LookUpItem and ISearchSubSupplier.LookUpItem never retuns null (but the empty list is valid).
        //Postcondition: LookUpItem never returns null (but the empty list is valid).
        public List<IItem> LookUpItem(ulong partnumber, string description)
        {
            List<IItem> items = cache.LookUpItem(partnumber, description);
            List<IItem> itemsToBeRemoved = new List<IItem>();

            //Checks for any items that have reached their expiration date.
            foreach (IItem item in items)
            {
                DateTime expirationDate = item.Hit;
                expirationDate = expirationDate.AddHours(cacheExpireTime);
                DateTime now = DateTime.Now;
                if (expirationDate.CompareTo(now) < 0)
                {
                    itemsToBeRemoved.Add(item);
                }
            }

            //Removes items (if any) that have reached their expiration date.
            if (itemsToBeRemoved.Count != 0)
            {
                cache.RemoveItems(itemsToBeRemoved);
                items = cache.LookUpItem(partnumber, description);
            }

            //If no valid items was found in cache check with sub supplier.
            //Add found items, if any, to the cashe.
            System.Console.WriteLine("size of item" + items.Count);
            if (items.Count == 0)
            {
                List<IItem> itemsToBeAdded = new List<IItem>();
                itemsToBeAdded = searchSubSupplier.LookUpItem(partnumber, description);
                
                foreach (IItem item in itemsToBeAdded)
                {
                    item.Hit = DateTime.Now;
                }
                cache.AddItems(itemsToBeAdded);
                items = cache.LookUpItem(partnumber, description);
            }

            return items;
        }

        public void SetCacheExpireTime(uint hours)
        {
            this.cacheExpireTime = hours;
        }
    }
}
